<?php
// 这是全局中间件

namespace app\admin\middleware;
use think\facade\Request;
use think\facade\Db; // 数据库的链接
class Codelogin
{
    public function handle($request, \Closure $next)
    {
        if (empty(@$_SERVER['HTTP_AUTHORIZATION'])) {
            return json(array('code' => 401, 'msg' => '请先登录!'));
        }
        $token = checkToken(str_replace("Bearer ", "", @$_SERVER['HTTP_AUTHORIZATION']));
        if ($token['code'] != 200) {
            return json(array('code' => 401, 'msg' => $token['msg']));
        }
        $adminuser = Db::name('admin')->where('id', $token['data']['UserID'])->find();

        // 判断密码
        if (@$adminuser['password'] != @$token['data']['pass']) {
            return json(array('code' => 401, 'msg' => '密码错误!'));
        }

        // 判断ip
        $ip = Request::instance()->ip();
        // if ($ip != $adminuser['ip']) {
        //     return json(array('code' => 401, 'msg' => '未知请求!'));
        // }

        $request->AdminId = $token['data']['UserID'];

        return $next($request);
    }
}
